
from fastapi import APIRouter, HTTPException, Query
from typing import List
from datetime import datetime

from app.schemas.simulation_result import SimulationResultCreate, SimulationResultOut
from app.crud import simulation_result as crud

router = APIRouter()

@router.post("/", response_model=SimulationResultOut)
async def create_result(data: SimulationResultCreate):
    result = await crud.create_simulation_result(data)
    return result

@router.get("/{result_id}", response_model=SimulationResultOut)
async def get_result(result_id: int):
    result = await crud.get_simulation_result_by_id(result_id)
    if not result:
        raise HTTPException(status_code=404, detail="Simulation result not found")
    return result

@router.get("/", response_model=List[SimulationResultOut])
async def list_results():
    return await crud.list_simulation_results()

@router.delete("/{result_id}")
async def delete_result(result_id: int):
    deleted = await crud.delete_simulation_result(result_id)
    if deleted == 0:
        raise HTTPException(status_code=404, detail="Simulation result not found")
    return {"message": "Deleted successfully"}

@router.get("/by_env_param/{env_param_id}", response_model=List[SimulationResultOut])
async def list_by_env(env_param_id: int):
    return await crud.list_by_env_param(env_param_id)

@router.get("/by_time_range/", response_model=List[SimulationResultOut])
async def list_by_time_range(
        env_param_id: int,
        start: datetime = Query(..., description="起始时间"),
        end: datetime = Query(..., description="结束时间")
):
    return await crud.list_by_env_param_and_time(env_param_id, start, end)

